package cn.rwklyd.BookKeeping.util;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;

@Component
@Slf4j
public class EmailUtils {

    @Value("${spring.mail.host}")
    private String host;

    @Value("${spring.mail.port}")
    private Integer port;

    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password;
    
    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送验证码邮件
     * @param to 收件人
     * @param code 验证码
     * @return 是否发送成功
     */
    @PreAuthorize("permitAll()")
    public boolean sendVerificationCode(String to, String code) {
        log.info("开始发送验证码邮件到: {}", to);
        try {
            String subject = "个人记账本 - 验证码";
            String content = "<div style='background-color:#f7f7f7;padding:20px;font-family:Arial,sans-serif;'>" +
                    "<div style='background-color:#ffffff;padding:20px;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,0.1);'>" +
                    "<div style='text-align:center;margin-bottom:20px;'>" +
                    "<h2 style='color:#FFCC33;margin:0;font-size:24px;'>个人记账本</h2>" +
                    "<div style='width:50px;height:3px;background:linear-gradient(135deg, #FFD84D, #FFCC33);margin:10px auto;border-radius:3px;'></div>" +
                    "</div>" +
                    "<p style='color:#333;font-size:16px;line-height:1.5;'>您好，您正在注册个人记账本账号，验证码为：</p>" +
                    "<div style='background:linear-gradient(135deg, #FFD84D, #FFCC33);color:#ffffff;font-size:26px;padding:15px;text-align:center;border-radius:8px;letter-spacing:8px;margin:20px 0;font-weight:bold;box-shadow:0 2px 5px rgba(255,204,51,0.3);'>" +
                    code +
                    "</div>" +
                    "<p style='margin-top:20px;font-size:14px;color:#666;line-height:1.5;'>验证码有效期为5分钟，请勿泄露给他人。</p>" +
                    "<div style='border-top:1px solid #eee;margin-top:20px;padding-top:15px;'>" +
                    "<p style='font-size:12px;color:#999;text-align:center;'>© " + java.time.Year.now().getValue() + " 个人记账本 - 让记账更简单</p>" +
                    "</div>" +
                    "</div></div>";

            return sendEmail(to, subject, content);
        } catch (Exception e) {
            log.error("验证码邮件发送失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 发送自定义内容邮件
     * @param to 收件人
     * @param subject 邮件主题
     * @param content 自定义内容
     * @param code 验证码（可选）
     * @return 是否发送成功
     */
    @PreAuthorize("permitAll()")
    public boolean sendCustomEmail(String to, String subject, String content, String code) {
        log.info("开始发送自定义邮件到: {}", to);
        try {
            String emailContent = "<div style='background-color:#f7f7f7;padding:20px;font-family:Arial,sans-serif;'>" +
                    "<div style='background-color:#ffffff;padding:20px;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,0.1);'>" +
                    "<div style='text-align:center;margin-bottom:20px;'>" +
                    "<h2 style='color:#FFCC33;margin:0;font-size:24px;'>个人记账本</h2>" +
                    "<div style='width:50px;height:3px;background:linear-gradient(135deg, #FFD84D, #FFCC33);margin:10px auto;border-radius:3px;'></div>" +
                    "</div>" +
                    "<div style='color:#333;font-size:16px;line-height:1.5;'>" + content + "</div>";
            
            // 如果提供了验证码，添加验证码样式
            if (code != null && !code.isEmpty()) {
                emailContent += "<div style='background:linear-gradient(135deg, #FFD84D, #FFCC33);color:#ffffff;font-size:26px;padding:15px;text-align:center;border-radius:8px;letter-spacing:8px;margin:20px 0;font-weight:bold;box-shadow:0 2px 5px rgba(255,204,51,0.3);'>" +
                        code +
                        "</div>";
            }
            
            emailContent += "<div style='border-top:1px solid #eee;margin-top:20px;padding-top:15px;'>" +
                    "<p style='font-size:12px;color:#999;text-align:center;'>此邮件由系统自动发送，请勿回复。</p>" +
                    "<p style='font-size:12px;color:#999;text-align:center;'>© " + java.time.Year.now().getValue() + " 个人记账本 - 让记账更简单</p>" +
                    "</div>" +
                    "</div></div>";

            return sendEmail(to, subject, emailContent);
        } catch (Exception e) {
            log.error("自定义邮件发送失败: {}", e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 发送邮件的通用方法
     */
    private boolean sendEmail(String to, String subject, String htmlContent) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            helper.setFrom(username);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);
            
            mailSender.send(message);
            log.info("邮件发送成功");
            return true;
        } catch (MessagingException e) {
            log.error("邮件发送失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 生成6位数字验证码
     */
    public String generateVerificationCode() {
        return RandomUtil.randomNumbers(6);
    }
}